package com.bdqn.t330.ch03.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession
        ;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory factory;

    static {
        try {
            //1.读取mybatis核心配置文件
            String resource = "mybatis-config.xml";
            //获取对mybatis-config.xml的输入流
            InputStream is = Resources.getResourceAsStream(resource);
            //2使用 SqlSessionFactoryBuilder读取配置文件并构建SqlSessionFactory实例
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSession createSqlSession() {
        return factory.openSession(false); //关闭自动提交开启事务
    }

    public static void closeSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}
